<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="nav-center">
        <text class="nav-title">美女看图</text>
      </view>
    </view>
    
    <!-- 分类选项夹 -->
    <CategoryTabs />
    
    <!-- 瀑布流图片列表 -->
    <view class="content">
      <Waterfall 
        v-if="imageList.length > 0"
        :images="imageList"
        :column-count="2"
        @image-click="handleImageClick"
      />
      
      <!-- 加载状态 -->
      <view class="loading-wrapper" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && !loading">
        <text class="load-more-text">上拉加载更多</text>
      </view>
      
      <!-- 没有更多 -->
      <view class="no-more" v-if="!hasMore && imageList.length > 0">
        <text class="no-more-text">没有更多了</text>
      </view>
    </view>
    
    <!-- 底部横幅广告（仅在 H5 端显示，小程序端由 tabbar 占据底部） -->
    <!-- #ifdef H5 -->
    <view class="bottom-ad-wrapper">
      <AdBanner position="bottom" />
    </view>
    <!-- #endif -->
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { onReachBottom, onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { useImageStore } from '@/stores/image'
import { getImageList } from '@/api/image'
import { showBannerAd } from '@/utils/ad-manager'
import Waterfall from '@/components/waterfall/waterfall.vue'
import AdBanner from '@/components/ad-banner/ad-banner.vue'
import CategoryTabs from '@/components/category-tabs/category-tabs.vue'

const imageStore = useImageStore()
const imageList = ref([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(20)

onMounted(() => {
  loadImageList()
  // 显示底部横幅广告
  setTimeout(() => {
    showBannerAd()
  }, 1000)
})

// 页面显示时刷新（从其他 tab 返回时）
onShow(() => {
  // 检查分类是否变化，如果变化则刷新
  if (imageList.value.length > 0) {
    // 可以根据需要决定是否刷新
  }
})

// 监听分类变化，自动刷新列表
watch(() => imageStore.currentCategory, (newCategory, oldCategory) => {
  if (oldCategory !== undefined && newCategory !== oldCategory) {
    loadImageList(true)
  }
})

// 加载图片列表
function loadImageList(isRefresh = false) {
  if (loading.value) return
  
  loading.value = true
  
  if (isRefresh) {
    currentPage.value = 1
    imageList.value = []
  }
  
  getImageList({
    page: currentPage.value,
    pageSize: pageSize.value,
    category: imageStore.currentCategory
  }).then(res => {
    if (res.code === 200 && res.data) {
      const newList = (res.data.list || []).map(item => ({
        id: item.id,
        title: item.title,
        thumbnail: item.thumbnail || item.url,
        image: item.url, // 后端使用 url 字段
        category: item.categoryId || item.categorySlug || "all",
        width: item.width,
        height: item.height,
        views: item.views || 0,
        likes: item.likes || 0,
        createTime: item.createdAt
      }))
      
      if (isRefresh) {
        imageList.value = newList
      } else {
        imageList.value.push(...newList)
      }
      
      imageStore.setImageList(imageList.value)
      
      // 判断是否还有更多
      hasMore.value = imageList.value.length < (res.data.total || 0)
      
      if (hasMore.value) {
        currentPage.value++
      }
    }
  }).catch(err => {
    console.error('加载图片列表失败:', err)
    uni.showToast({
      title: err.message || '加载失败',
      icon: 'none'
    })
  }).finally(() => {
    loading.value = false
  })
}

// 点击图片
function handleImageClick(image) {
  uni.navigateTo({
    url: `/pages/detail/detail?id=${image.id}`
  })
}

// 下拉刷新
onPullDownRefresh(() => {
  loadImageList(true).finally(() => {
    uni.stopPullDownRefresh()
  })
})

// 上拉加载更多
onReachBottom(() => {
  if (hasMore.value && !loading.value) {
    loadImageList()
  }
})
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: calc(50px + env(safe-area-inset-bottom)); /* 为 tabbar 留出空间 */
}

.bottom-ad-wrapper {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  z-index: 99;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.nav-center {
  text-align: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.content {
  padding: 20rpx 0;
}

.loading-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.load-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.load-more-text,
.no-more-text {
  font-size: 28rpx;
  color: #999;
}
</style>

